
import distributedKVStore from '@ohos.data.distributedKVStore';

let kvManager;
export class KvStoreModel {
  public kvManager: distributedKVStore.KVManager = undefined
  public kvStore: distributedKVStore.DeviceKVStore = undefined

  createKvStore(context, callback) {
    if ((typeof (this.kvStore) !== 'undefined')) {
      callback()
      return
    }
    try {
      const kvManagerConfig = {
        context: context,
        userInfo: {
          userId: '0',
          userType: 0
        },
        bundleName: 'com.example.obike'
      };
      kvManager = distributedKVStore.createKVManager(kvManagerConfig);
      console.info('KVStore Succeeded in creating KVManager.');
      const options = {
        createIfMissing: true, // 当数据库文件不存在时是否创建数据库，默认创建
        encrypt: false, // 设置数据库文件是否加密，默认不加密
        backup: false, // 设置数据库文件是否备份，默认备份
        autoSync: true, // 设置数据库文件是否自动同步。默认为false，即手动同步；设置为true时，表示自动同步
        kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建的数据库类型，默认为多设备协同数据库
        securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库安全级别
      };
      // 数据库唯一标识符PilotKVStoreID
      kvManager.getKVStore('PilotKVStoreID', options, (err, kvStore) => {
        if (err) {
          console.error(`KVStore Failed to get KVStore. Code:${err.code},message:${err.message}`);
          return;
        }
        this.kvStore = kvStore
        console.info('KVStore Succeeded in getting KVStore.');
      });
    } catch (e) {
      console.error(`An unexpected error occurred KEY_TEST_STRING_ELEMENT. Code:${e.code},message:${e.message}`);
    }

  }

  put(key, value) {

    // this.kvStore.put(key, value).then((data) => {
    //
    // }).catch((err) => {
    //
    // })
  }

  get(key,callback)
  {

  }

  setOnMessageReceivedListener(context, msg, callback) {

    this.createKvStore(context, () => {

      this.kvStore.on('dataChange', 1, (data) => {

        let entries = data.insertEntries.length > 0 ? data.insertEntries : data.updateEntries
        for (let i = 0; i < entries.length; i++) {
          if (entries[i].key === msg) {
            let value = <string> entries[i].value.value

            callback(value)
            return
          }
        }
      })

    })
  }
}